import json
import random

import django_redis
from django.http import HttpResponse, JsonResponse
from django.views import View
from fdfs_client.client import Fdfs_client, get_tracker_conf

from libs.captcha.captcha.captcha import captcha


# Create your views here.


class ImageCodeView(View):

    def get(self, request, uuid):
        tracker_conf = get_tracker_conf(r'utils/fastdfs/fdfs_tracker.conf')
        client = Fdfs_client(tracker_conf)
        print(client)


        text, image = captcha.generate_captcha()

        redis_cli = django_redis.get_redis_connection('image_code')

        redis_cli.setex(uuid, 60, text)

        return HttpResponse(content=image, content_type='image/jpeg')


class SMSCodeView(View):

    def get(self, request, mobile):

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        if not all([image_code, uuid]):
            return JsonResponse(data={'code': 400, 'errmsg': '参数错误'})

        redis_cli = django_redis.get_redis_connection('sms_code')
        redis_image_code = redis_cli.get(uuid)

        if redis_image_code is None:
            return JsonResponse(data={'code': 400, 'errmsg': '验证码失效'})

        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_cli.delete(uuid)
        except Exception as e:
            pass

        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse(data={'code': 400, 'errmsg': '验证码错误'})

        sms_code = '%04d' % random.randint(0, 999999)

        pl = redis_cli.pipeline()

        # redis_cli.setex(mobile, 60, sms_code)
        # redis_cli.setex(f'send_flag_{mobile}', 60, '1')
        pl.setex(mobile, 60, sms_code)
        pl.setex(f'send_flag_{mobile}', 60, '1')
        pl.execute()

        # sendTemplateSMS('17876777918', [sms_code, 1], 1)
        # tasks.delay.send_sms_code(mobile, sms_code)
        print(f'phone:{mobile},code:{sms_code}')
        return JsonResponse({'code': 0, 'errmsg': ''})
